package com.sp.api.springbootapi.distributedLock;

import com.sp.api.springbootapi.service.CustomLockServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by weidewang on 2018/7/3
 */
@Service
public class CustomMySQLLock implements Lock {
    private static final Integer KEY = 1;
    
    @Autowired
    private CustomLockServiceImpl customLockServiceImpl;
    
    @Override
    public void lock() {
        if (!tryLock()){
            try {
                Thread.sleep(new Random().nextInt(10)+1);
            } catch (InterruptedException e) {
//                e.printStackTrace();
            }
            lock();
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        try {
            customLockServiceImpl.insert(KEY);
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        try {
            customLockServiceImpl.deleteById(KEY);
        } catch (Exception e) {
//            e.printStackTrace();
        } finally {
        }

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
